<?php

/*
  APP KUDOS. Project of SSUI course.
  2011-1
  
  Tiffany Ng
  Victor Rivera
  Sypraseuth Vandy
  Justine Yang
 */

// set up database info
//$usr = "kudosadmin";
//$pwd = "ssui2011!";
//$db = "appkudos";
//$host = "oigetitg.ipagemysql.com";

$usr = "ak1";
$pwd = "appkudos!";
$db = "appkudos1";
$host = "yangjustine.startlogicmysql.com";

//Build a JSON structure with an error message
function ERROR($message){
  /*
    0 -> No parameter specified.
    1 -> No function found.
    otherwise -> mysql_error or function error message.
   */
  $e = array('ERROR' => $message);
  die(json_encode($e));
}
//Build a JSON structure with an successful notification message
function SUCCESSFUL(){
  $e = array('SUCCESSFUL' => '');
  die(json_encode($e));
}

// establish connection
$connection = mysql_connect($host,$usr,$pwd);
if (!$connection) { ERROR(mysql_error()); }

//executes a sql query (this is a test)
function executeQuery($sql) { 
  global $connection, $db;
  $users = mysql_db_query($db,"$sql",$connection);
  
  if (!$users) {
	ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($users))
      {
	print(json_encode($information));
	print(',');
      }
  }
} 
//QUERIES

/*createUser: creates an user.
  Precondition -> Value username must not be null (empty).
  Postcondition --> New user is created.
 */
function createUser($username,$firstname,$lastname) {
  global $connection, $db;

 $sql_query = "INSERT INTO `User` (`username`, `firstname`,`lastname`,`dateCreated`) VALUES ('". $username ."', '". $firstname ."','". $lastname ."',CURRENT_TIMESTAMP);";

  $inserted = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$inserted) {
     ERROR(mysql_error());
  }
}

/*addFriend: Add a username2 to username1 friend's list.
  Precondition -> true.
  Postcondition --> New friendship is created, if both usernames exist.
 */
function addFriend($username1,$username2) {
  global $connection, $db;
  
  $sql_query = "INSERT INTO `IsFriend` (`username1`, `username2`,`dateAdded`) VALUES 
               ('". $username1 ."', '". $username2 ."',CURRENT_TIMESTAMP);";
  
  $inserted = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$inserted) {
    ERROR(mysql_error());
  }
}


function addFriend2($username1,$username2) {
  global $connection, $db;
  
  //check that username1 != username2
  if ($username1 != $username2){
    
    //Check if username1/2 exist in table User
    $sql_username1Exists = "SELECT * FROM `User` WHERE username='" . $username1 . "';";
    $sql_username2Exists = "SELECT * FROM `User` WHERE username='" . $username2 . "';";
    $u1 = mysql_db_query($db,"$sql_username1Exists",$connection);
    $u2 = mysql_db_query($db,"$sql_username2Exists",$connection);
    
    if (!($u1 and $u2)) {
      ERROR(mysql_error());
    }
    else{
      if (mysql_num_rows($u1) == 0 or mysql_num_rows($u2) == 0)
	{
	  ERROR("Username1/2 do(es) not exist.");
	}
      else{
	//both usernames exist, so it is possible to create the friendship.
	
	$sql_query = "INSERT INTO `IsFriend` (`username1`, `username2`,`dateAdded`) VALUES ('". $username1 ."', '". $username2 ."',CURRENT_TIMESTAMP);";
	
	$inserted = mysql_db_query($db,"$sql_query",$connection);
	
	if (!$inserted) {
	  ERROR(mysql_error());
	}
	else{
	  SUCCESSFUL();
	}
      }
    }
  }else{
     ERROR("Cannot be friends with yourself");
  }
}

/*joinGroup: Join username into groupid.
  Precondition -> true.
  Postcondition --> username is joined into groupid, if username and group exist.
 */
function joinGroup($username,$groupid) {
  global $connection, $db;
  
  $sql_query = "INSERT INTO `JoinedGroup` (`username`, `groupid`,`dateJoined`) VALUES 
                ('". $username ."', ". $groupid .",CURRENT_TIMESTAMP);";
  
  $inserted = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$inserted) {
    ERROR(mysql_error());
  }
}

function joinGroup2($username,$groupid) {
  global $connection, $db;
  
  //Check if username and groupid exist in table User and Group, respectively.
  $sql_usernameExists = "SELECT * FROM `User` WHERE username='" . $username . "';";
  $sql_groupExists = "SELECT * FROM `Group` WHERE groupid='" . $groupid . "';";
  $u1 = mysql_db_query($db,"$sql_usernameExists",$connection);
  $u2 = mysql_db_query($db,"$sql_groupExists",$connection);
  
  if (!($u1 and $u2)) {
     ERROR(mysql_error());
  }
  else{
    if (mysql_num_rows($u1) == 0 or mysql_num_rows($u2) == 0)
      {
	    ERROR("Username or groupid do not exist.");
      }
    else{
      //Usernames and group exist, so it is possible to join username into groupid.
      $sql_query = "INSERT INTO `JoinedGroup` (`username`, `groupid`,`dateJoined`) VALUES ('". $username ."', ". $groupid .",CURRENT_TIMESTAMP);";
      
      $inserted = mysql_db_query($db,"$sql_query",$connection);
      
      if (!$inserted) {
	ERROR(mysql_error());
      }else
	{
	  SUCCESSFUL();
	}
    }
  }
}

/*leaveGroup: Username leaves a groupid.
  Precondition -> true.
  Postcondition --> Groupid is left by Username, if username and group exist.
 */
function leaveGroup($username,$groupid) {
  global $connection, $db;
  
  //Check if username is in groupid.
  $sql_relationExists = "SELECT * FROM `JoinedGroup` WHERE username='" . $username . "' and groupid = ". $groupid .";";
  $u1 = mysql_db_query($db,"$sql_relationExists",$connection);
  
  if (!$u1) {
        ERROR(mysql_error());
  }
  else{
    if (mysql_num_rows($u1) == 0)
      {
	    ERROR("Username isn't in groupid.");
      }
    else{
      //Usernames and group exist, so it is possible to join username into groupid.
      $sql_query = "DELETE FROM `JoinedGroup` WHERE username='" . $username . "' and groupid = ". $groupid .";";
      
      $inserted = mysql_db_query($db,"$sql_query",$connection);
      
      if (!$inserted) {
	      ERROR(mysql_error());
      }
    }
  }
}
  
/*getFriendsUser: username's friend list.
  Precondition -> true.
  Postcondition --> username's friend list.
 */
function getFriendsUser($username) {
  global $connection, $db;
  
  $sql_query = "SELECT User.username, User.firstname, User.lastname, IsFriend.dateAdded 
                FROM `User`, `IsFriend` 
                WHERE IsFriend.username1='" . $username . "' and IsFriend.username2 = User.username;";
  //$sql_query = "SELECT * FROM `IsFriend`;";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getMyGroups: 
  Precondition -> true.
  Postcondition --> information of the groups where username is joined.
 */
function getMyGroups($username) {
  global $connection, $db;

  $sql_query = "SELECT Group.groupid, Group.name, Group.desc, JoinedGroup.dateJoined, Category.catid, Category.categoryName 
                FROM `JoinedGroup`, `Group`, `Category` 
                WHERE Group.category = Category.catid and JoinedGroup.username='" . $username . "' and JoinedGroup.groupid = Group.groupid;";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getAppsByUser: username's app list.
  Precondition -> true.
  Postcondition --> App name, app id, description, is Favorite.
 */
function getAppsByUser($username) {
  global $connection, $db;
  
  $sql_query = "SELECT App.name, App.appid, App.desc, Installed.IsFavorite, Installed.dateInstalled
                FROM `App`, `Installed` 
                WHERE Installed.username='" . $username . "' and Installed.appid = App.appid;";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*addFavApp: username's app becomes favorite.
  Precondition -> true.
  Postcondition --> username's app becomes favorite.
 */
function addFavApp($username,$appid) {
  global $connection, $db;
  
  $sql_query = "UPDATE `Installed` 
             SET isFavorite=1
             WHERE Installed.username='" . $username . "' and Installed.appid = ". $appid .";";
  
  $info = mysql_db_query($db,"$sql_query",$connection);  
  if (!$info){
    ERROR(mysql_error());
  }
}

/*retrieveFavApps: username's favorite apps.
  Precondition -> true.
  Postcondition --> username's favorite apps.
 */
function retrieveFavApps($username) {
  global $connection, $db;
  
  $sql_query = "SELECT * FROM `App`, `Installed` WHERE Installed.username='" . $username . "' and Installed.appid = App.appid and Installed.isFavorite = 1;";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*removeFavApp: username's appid is taken off from favorite list.
  Precondition -> true.
  Postcondition --> username's appid is taken off from favorite list.
 */
function removeFavApp($username,$appid) {
  global $connection, $db;
  
  $sql_query = "UPDATE `Installed` 
             SET isFavorite=0
             WHERE Installed.username='" . $username . "' and Installed.appid = ". $appid .";";
  
  $info = mysql_db_query($db,"$sql_query",$connection); 
  if (!$info){
    ERROR(mysql_error());
  }
}

/*getRecentApps: username's recent (one month ago) installed app.
  Precondition -> true.
  Postcondition --> username's recent (one month ago) installed app.
 */
function getRecentApps($username) {
  global $connection, $db;
  $sql_query = "SELECT App.name, App.appid, App.desc, Installed.isFavorite, Installed.dateInstalled FROM `App`, `Installed` WHERE Installed.username='" . $username . "' and Installed.appid = App.appid and Installed.dateInstalled BETWEEN SUBTIME(CURRENT_TIMESTAMP,'30 0:0:0') AND CURRENT_TIMESTAMP LIMIT 5;";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getUserProfile: gets all info for this user
  Precondition -> true.
  Postcondition --> username's, firstname, lastname, and dateCreated
 */
function getUserProfile($username) {
  global $connection, $db;
  
  $sql_query = "SELECT username, firstname, lastname, dateCreated FROM `User` WHERE username='".$username."'";
  
  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getRecsToUser: Gets the recommendations made to user.
  Precondition -> true.
  Postcondition --> sender, appname, appid, recommendation, recid, isGroupRecipient
 */
function getRecsToUser($username){
  global $connection, $db;
  
  $sql_query = "SELECT SendRec.sender, App.name, App.appid, Recommendation.message, Recommendation.recid, 
                       SendRec.isGroupReceipient, Recommendation.dateSent
                FROM `SendRec`, `Recommendation`, `App`
                WHERE SendRec.recipient = '".$username."' and SendRec.recid = Recommendation.recid and
		Recommendation.appid = App.appid ORDER BY dateSent DESC;";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
} 

/*getRecsFromUser: Gets the recommendations made by user.
  Precondition -> true.
  Postcondition --> recipient, appname, appid, recommendation, recid, isGroupRecipient
 */
function getRecsFromUser($username){
  global $connection, $db;
  
  $sql_query = "SELECT SendRec.recipient, App.name, App.appid, Recommendation.message, Recommendation.recid, 
                       SendRec.isGroupReceipient, Recommendation.dateSent
                FROM `SendRec`, `Recommendation`, `App`
                WHERE SendRec.sender = '".$username."' and SendRec.recid = Recommendation.recid and
		Recommendation.appid = App.appid ORDER BY dateSent DESC;";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getRecsForUser: Gets the recommendations made to or by user.
  Precondition -> true.
  Postcondition --> recipient, sender, appname, appid, recommendation, recid, isGroupRecipient
 */
function getRecsForUser($username){
  global $connection, $db;
  
  $sql_query = "SELECT SendRec.recipient, SendRec.sender, App.name, App.appid, Recommendation.message, Recommendation.recid, SendRec.isGroupReceipient, Recommendation.dateSent
                FROM `SendRec`, `Recommendation`, `App`
                WHERE (SendRec.sender = '$username' or SendRec.recipient = '$username') and SendRec.recid = Recommendation.recid and
		Recommendation.appid = App.appid ORDER BY dateSent DESC;";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getRecentRecsForUser: Gets the most recent 5 recommendations made to or from this user
  Precondition -> true.
  Postcondition --> sender, appname, appid, recommendation, recid, isGroupRecipient
 */
function getRecentRecsForUser($username){
  global $connection, $db;
  
  $sql_query = "SELECT DISTINCT SendRec.sender, App.name, SendRec.recipient, App.appid, 				Recommendation.message, Recommendation.recid, SendRec.isGroupReceipient, Recommendation.dateSent
				FROM  `SendRec` ,  `Recommendation` ,  `App` 
				WHERE (SendRec.recipient =  '$username'
				OR SendRec.sender =  '$username')
				AND (SendRec.recid = Recommendation.recid
				AND Recommendation.appid = App.appid)
				ORDER BY dateSent DESC LIMIT 5";

  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
} 

/*getNotInstalledApp: Gets the apps do not installed by user.
  Precondition -> true.
  Postcondition --> nameApp, idApp, desc
 */
function getNotInstalledApp($username){
  global $connection, $db;
  
  $sql_query = "SELECT `name`, `appid`, `desc` 
                FROM `App`
                WHERE `appid` NOT IN 
                      (SELECT `appid` FROM `Installed` WHERE `username` = '". $username ."');";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*getAppsInDB: Gets the apps in db
  Precondition -> true.
  Postcondition --> nameApp, idApp, desc
 */
function getAppsInDB(){
  global $connection, $db;
  
  $sql_query = "SELECT `name`, `appid`, `desc` 
                FROM `App`";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

/*searchForUser: Gets users which contains $keyword.
  Precondition -> true.
  Postcondition --> username, firstname, lastname, dateCreated
 */
function searchForUser($keyword){
  global $connection, $db;
  
  $sql_query = "SELECT `username`, `firstname`, `lastname`, `dateCreated` 
                FROM `User`
                WHERE (`username` LIKE '%". $keyword ."%' or
                       `firstname` LIKE '%". $keyword ."%' or
                        `lastname` LIKE '%". $keyword ."%');";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

function getAppInfo($appid) {
  global $connection, $db;
  
  $sql_query = "SELECT `name`, `desc` FROM `App`
                WHERE App.appid=". $appid .";";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

function getAllUsers(){
  global $connection, $db;
  
  $sql_query = "SELECT * FROM `User`";


  $info = mysql_db_query($db,"$sql_query",$connection);
  
  if (!$info) {
    ERROR(mysql_error());
  }else{
    while($information = mysql_fetch_array($info))
      {
	print(json_encode($information));
	print(',');
      }
  }  
}

function test($username,$jsonArray) {
  global $connection, $db;                 
  global $connection, $db;      
  $obj = json_decode($jsonArray);
  $sql_query = "INSERT INTO `User` (`username`,`firstname`,`lastname`,`dateCreated`)
                 VALUES ('hola','". $jsonArray."','Test',CURRENT_TIMESTAMP);";
  $info = mysql_db_query($db,"$sql_query",$connection); 
  if (!$info){
    ERROR(mysql_error());
  }
}

/*addApp: Add a newly installed app into the db
 */
function addApp($username,$appid, $appname, $appdesc, $new) {
  global $connection, $db;                 
    $sql_query = "INSERT INTO `Installed` (`username`,`appid`,`isFavorite`,`dateInstalled`)
                 VALUES ('".$username."',".$appid.",0,CURRENT_TIMESTAMP);";
    $info = mysql_db_query($db,"$sql_query",$connection); 
  
}
/*addNewApp: If the appid isn't in app/installed table, it's inserted.
 */
function addNewApp($username,$appid, $appname, $appdesc, $new) {
  global $connection, $db;
    $sql_query = "INSERT INTO `App` (`appid`, `name`, `desc`) VALUES (".$appid.",
                       '".$appname."','".$appdesc."');";
    $info = mysql_db_query($db,"$sql_query",$connection); 
    $sql_query = "INSERT INTO `Installed` (`username`,`appid`,`isFavorite`,`dateInstalled`)
                 VALUES ('".$username."',".$appid.",0,CURRENT_TIMESTAMP);";
    $info = mysql_db_query($db,"$sql_query",$connection); 
}

/***  
	Takes an list of new apps and adds them all to the App and Install tables
	Each app includes: $appid, $name, $desc
	Example usage: 
	$jsontest = '{"app1":{"appid":88888, "name":"testerApp1", "desc":"testing 1"},"app2":{"appid":89, "name":"testerApp2", "desc":"testing 2"}}';
	addNewApps("Vic", $jsontest);
***/
function addNewApps($username, $JSONapplist){
	global $connection, $db;
	$applist = json_decode($JSONapplist, true);
//	print_r($applist);
	foreach($applist as $app){
		$appid = $app['appid'];
		$appname = $app['name'];
		$appdesc = $app['desc'];

		// Add to Apps table since it doesn't exist yet
		$sql_query = "INSERT INTO `App` (`appid`, `name`, `desc`) VALUES ('$appid','$appname','$appdesc');";
		$info = mysql_db_query($db,"$sql_query",$connection);
		
		// Install app for user
		$sql_query = "INSERT INTO `Installed` (`username`,`appid`,`isFavorite`,`dateInstalled`) VALUES ('$username','$appid',0,CURRENT_TIMESTAMP);";
	    $info = mysql_db_query($db,"$sql_query",$connection); 
	   	
		if (!$info){
	    	ERROR(mysql_error());
			return;
		}
	}
}


/*
 	Takes an list of existing apps and installs them for this user
	Each app includes: $appid
	Example usage: 
	$jsontest = '{"app1":{"appid":88888},"app2":{"appid":89,}}';
	addApps("Vic", $jsontest);
*/
function addApps($username, $JSONapplist){
	global $connection, $db;
	$applist = json_decode($JSONapplist, true);
	foreach($applist as $app){
		$appid = $app['appid'];

		// Install each app for user
		$sql_query = "INSERT INTO `Installed` (`username`,`appid`,`isFavorite`,`dateInstalled`) VALUES ('$username','$appid',0,CURRENT_TIMESTAMP);";
	    $info = mysql_db_query($db,"$sql_query",$connection); 
	   
		if (!$info){
	    	ERROR(mysql_error());
			return;
		}
	}
}



/*removeApp: removes appid to username installed list.
  Precondition -> true.
  Postcondition --> 
 */
function removeApp($username,$appid) {
  global $connection, $db;
  
  $sql_query = "DELETE FROM `Installed` 
                 WHERE `username` = '".$username."' and `appid`=".$appid.";";
  
  $info = mysql_db_query($db,"$sql_query",$connection); 
  if (!$info){
    ERROR(mysql_error());
  }
}

//Handler for passing to Android
switch($_REQUEST['function']){
	case 'test':
		if($_REQUEST['username']=='' or $_REQUEST['jsonArray']==''){
			ERROR("Missing fields");
		}else{
		  test($_REQUEST['username'], $_REQUEST['jsonArray']);
		}
		break;
	case 'addApp':
		if($_REQUEST['username']=='' or $_REQUEST['appid']=='' or $_REQUEST['appname']=='' or $_REQUEST['appdesc']==''){
			ERROR("Missing fields");
		}else{
		  addApp($_REQUEST['username'], $_REQUEST['appid'], $_REQUEST['appname'], $_REQUEST['appdesc']);
		}
		break;
	case 'addNewApp':
		if($_REQUEST['username']=='' or $_REQUEST['appid']=='' or $_REQUEST['appname']=='' or $_REQUEST['appdesc']==''){
			ERROR("Missing fields");
		}else{
		  addNewApp($_REQUEST['username'], $_REQUEST['appid'], $_REQUEST['appname'], $_REQUEST['appdesc']);
		}
		break;
	case 'getAppInfo':
		if($_REQUEST['appid']==''){
			ERROR("Missing fields");
		}else{
			getAppInfo($_REQUEST['appid']);
		}
		break;
	case 'createUser':
		if($_REQUEST['username']=='' or $_REQUEST['firstname']=='' or $_REQUEST['lastname']==''){
			ERROR("Missing fields");
		}else{
			createUser($_REQUEST['username'], $_REQUEST['firstname'], $_REQUEST['lastname']);
		}
		break;
	case 'addFriend':
		if($_REQUEST['username1']=='' or $_REQUEST['username2']==''){
			ERROR("Missing fields");
		}else{
			addFriend($_REQUEST['username1'], $_REQUEST['username2']);
		}
		break;
	case 'joinGroup':
		if($_REQUEST['username']=='' or $_REQUEST['groupid']==''){
			ERROR("Missing fields");
		}else{
			joinGroup($_REQUEST['username'], $_REQUEST['groupid']);
		}
		break;
	case 'leaveGroup':
		if($_REQUEST['username']=='' or $_REQUEST['groupid']==''){
			ERROR("Missing fields");
		}else{
			leaveGroup($_REQUEST['username'], $_REQUEST['groupid']);
		}
		break;
	case 'getFriendsUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getFriendsUser($_REQUEST['username']);
		}
		break;		
	case 'getMyGroups':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getMyGroups($_REQUEST['username']);
		}
		break;		
	case 'getAppsByUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getAppsByUser($_REQUEST['username']);
		}
		break;
	case 'addFavApp':
		if($_REQUEST['username']=='' or $_REQUEST['appid']==''){
			ERROR("Missing fields");
		}else{
			addFavApp($_REQUEST['username'], $_REQUEST['appid']);
		}
		break;		
        case 'removeApp':
		if($_REQUEST['username']=='' or $_REQUEST['appid']==''){
			ERROR("Missing fields");
		}else{
			removeApp($_REQUEST['username'], $_REQUEST['appid']);
		}
		break;		
	case 'retrieveFavApps':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			retrieveFavApps($_REQUEST['username']);
		}
		break;
	case 'removeFavApp':
		if($_REQUEST['username']=='' or $_REQUEST['appid']==''){
			ERROR("Missing fields");
		}else{
			removeFavApp($_REQUEST['username'], $_REQUEST['appid']);
		}
		break;		
	case 'getRecentApps':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getRecentApps($_REQUEST['username']);
		}
		break;
	case 'getUserProfile':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getUserProfile($_REQUEST['username']);
		}
		break;	
	case 'getRecsToUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getRecsToUser($_REQUEST['username']);
		}
		break;	
	case 'getRecsFromUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getRecsFromUser($_REQUEST['username']);
		}
		break;
	case 'getRecentRecsForUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getRecentRecsForUser($_REQUEST['username']);
		}
		break;		
	case 'getRecsForUser':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getRecsForUser($_REQUEST['username']);
		}
		break;		
		
	case 'getNotInstalledApp':
		if($_REQUEST['username']==''){
			ERROR("Missing fields");
		}else{
			getNotInstalledApp($_REQUEST['username']);
		}
		break;
	case 'getAppsInDB':
			getAppsInDB();
		break;
	case 'searchForUser':
		if($_REQUEST['keyword']==''){
			ERROR("Missing fields");
		}else{
			searchForUser($_REQUEST['keyword']);
		}
		break;
	case 'getAllUsers':
	  getAllUsers();
		break;
	case 'addNewApps':
		if($_REQUEST['username']=='' || $_REQUEST['JSONapplist']==''){
			ERROR("Missing fields");
		}else{
			addNewApps($_REQUEST['username'], $_REQUEST['JSONapplist']);
		}
		break;
	case 'addApps':
		if($_REQUEST['username']=='' || $_REQUEST['JSONapplist']==''){
			ERROR("Missing fields");
		}else{
			addApps($_REQUEST['username'], $_REQUEST['JSONapplist']);
		}
		break;
		
    case 'executeQuery':
      executeQuery("DELETE FROM `User` WHERE `username`='hola'");

      //executeQuery("SELECT `firstname` FROM `User` WHERE `username`='hola'");
	  break;
}

//executeQuery("SELECT username,`username2` FROM `IsFriend`;");

//createUser($username,$firstname,$lastname)
//addFriend($username1,$username2)
//joinGroup($username,$groupid)
//leaveGroup($username,$groupid)
//retrieveFriendList($username)
//retrievePersonalGroups($username)
//retrieveAppList($username)
//addFavApp($username,$appid)
//retrieveFavApps($username)
//removeFavApp($username,$appid)
//retrievePersonalRecentApps($username)


mysql_close($connection);

?>